import { EventClass } from "@lib/alen-helper/node/baseClass";
import { Tray } from "electron";
import { Subscription, fromEvent } from "rxjs";
import { Application } from "../application/application";


export class TrayOperator extends EventClass<Runtime.Operator.EventData<Runtime.OperatorCls.Tray.Events>> implements Runtime.OperatorCls.Tray {

    readonly type = 'tray';

    constructor(
        public readonly id: string,
        public readonly app: Application,
        options: Partial<Runtime.OperatorCls.Tray.Options>,
        BaseOptions?: Partial<EventClass.BaseOptions>
    ) {
        super('TrayOperator', BaseOptions);
        this._options = Object.assign(this._options, options);
    }

    private _options: Runtime.OperatorCls.Tray.Options = {
        icon: '',
        toolTip: null,
    };
    private _src: Tray | null = null;

    get options() {
        return this._options;
    }

    private _sub: Subscription | null = null;
    private _unSubs() {
        if (this._sub) this._sub.unsubscribe();
        this._sub = null;
    }

    setIcon(icon: string) {
        if (!this._src) return false;
        this._src.setImage(icon);
        this._options.icon = icon;
        return true;
    }

    setToolTip(txt: string | null) {
        if (!this._src) return false;
        this._src.setToolTip(txt ? txt : '');
        this._options.toolTip = txt;
        return true;
    }

    start() {
        if (this._src) return true;
        if (!this.options.icon) throw this._err('参数出错', '没有图标');
        this._unSubs();
        this._src = new Tray(this.options.icon);
        if (this.options.toolTip) this.setToolTip(this.options.toolTip);
        this._sub = fromEvent(this._src, 'click', e => e as Electron.KeyboardEvent)
            .subscribe(e => {
                this.triggerEvent('click', null);
            });
        this._sub.add(
            fromEvent(this._src, 'double-click', e => e as Electron.KeyboardEvent)
                .subscribe(e => {
                    this.triggerEvent('double-click', null);
                })
        );
        this._sub.add(
            this.event('destroy')
                .subscribe(() => {
                    this._unSubs();
                    this.destroyEvent();
                })
        );
        this.triggerEvent('start', null);
        return true;
    }

    destroy() {
        if (!this._src) return true;
        this._src.destroy();
        this._src = null;
        this.triggerEvent('destroy', null);
        return true;
    }

}